<template>
  <div class="billing-rule-manage">
    <div class="page-header">
      <i class="el-icon-money"></i>
      <span>计费规则管理</span>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入规则名称搜索"
        class="search-input"
        clearable
        prefix-icon="el-icon-search"
        @clear="handleSearch"
        @keyup.enter.native="handleSearch"
      >
      </el-input>
      <div class="button-group">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="handleSearch">查询</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="!selectedRows.length">删除</el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
      <el-table-column prop="ruleName" label="规则名称" min-width="120" align="center"></el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'warning' : 'success'" size="small">
            {{ scope.row.status === 1 ? '分段计费' : '全时段' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="计费时段" min-width="280" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.status === 2">
            <span>全时段</span>
          </template>
          <template v-else>
            <template v-if="scope.row.stageBillings && scope.row.stageBillings.length">
              <span>
                {{ formatStageTimeSlots(scope.row.stageBillings) }}
              </span>
            </template>
            <template v-else>
              <span>暂无分段数据</span>
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="单价" min-width="280" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.status === 2">
            <span>全天 (￥1.0,￥0.6)</span>
          </template>
          <template v-else>
            <template v-if="scope.row.stageBillings && scope.row.stageBillings.length">
              <span>
                {{ formatStagePrices(scope.row.stageBillings) }}
              </span>
            </template>
            <template v-else>
              <span>暂无费率数据</span>
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="formData.ruleName" placeholder="请输入规则名称"></el-input>
        </el-form-item>

        <el-form-item label="计费方式" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">分段计费</el-radio>
            <el-radio :label="2">全时段计费</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="formData.status === 2">
          <el-form-item label="统一费率" prop="uniformRate">
            <el-input-number 
              v-model="formData.uniformRate"
              :precision="2"
              :step="0.1"
              :min="0"
              controls-position="right"
            ></el-input-number>
            <span class="unit-label">元/度</span>
          </el-form-item>
          <el-form-item label="服务费" prop="serviceRate">
            <el-input-number 
              v-model="formData.serviceRate"
              :precision="2"
              :step="0.1"
              :min="0"
              controls-position="right"
            ></el-input-number>
            <span class="unit-label">元/度</span>
          </el-form-item>
        </template>

        <template v-else>
          <div class="stage-billing-section">
            <div class="section-header">
              <span class="section-title">阶段计费设置</span>
              <el-button type="primary" size="small" @click="handleAddStage">添加阶段</el-button>
            </div>
            
            <el-table
              :data="stageBillingData"
              border
              style="width: 100%; margin-top: 15px;"
            >
              <el-table-column label="时段类型" width="120" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.time_slot_type" placeholder="请选择">
                    <el-option label="尖时段" value="尖"></el-option>
                    <el-option label="峰时段" value="峰"></el-option>
                    <el-option label="平时段" value="平"></el-option>
                    <el-option label="谷时段" value="谷"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              
              <el-table-column label="开始时间" width="180" align="center">
                <template slot-scope="scope">
                  <el-time-picker
                    v-model="scope.row.start_time"
                    format="HH:mm"
                    placeholder="开始时间"
                    style="width: 150px;"
                  ></el-time-picker>
                </template>
              </el-table-column>
              
              <el-table-column label="结束时间" width="180" align="center">
                <template slot-scope="scope">
                  <el-time-picker
                    v-model="scope.row.end_time"
                    format="HH:mm"
                    placeholder="结束时间"
                    style="width: 150px;"
                  ></el-time-picker>
                </template>
              </el-table-column>
              
              <el-table-column label="电费单价" width="150" align="center">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.electricity_fee"
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    controls-position="right"
                  ></el-input-number>
                </template>
              </el-table-column>
              
              <el-table-column label="服务费" width="150" align="center">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.charging_service_fee"
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    controls-position="right"
                  ></el-input-number>
                </template>
              </el-table-column>
              
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button 
                    type="text" 
                    @click="handleDeleteStage(scope.$index)"
                    :disabled="stageBillingData.length <= 1"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>

        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            :rows="3"
            v-model="formData.description"
            placeholder="请输入规则描述">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleDialogClose">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'BillingRuleManage',
  data() {
    return {
      searchQuery: '',
      loading: false,
      submitLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '新增计费规则',
      formData: {
        id: null,
        ruleName: '',
        status: 2,
        description: '',
        uniformRate: 1.0,
        serviceRate: 0.6,
      },
      formRules: {
        ruleName: [
          { required: true, message: '请输入规则名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      stageBillingData: [{
        id: null,
        time_slot_type: '尖',
        start_time: '00:00:00',
        end_time: '00:00:00',
        electricity_fee: '0.00',
        charging_service_fee: '0.00',
        billing_rule_id: null,
        is_all_day: 0
      }]
    }
  },
  methods: {
    loadData() {
      this.loading = true;
      this.$axios.get('/api/billingRule/list', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery ? this.searchQuery.trim() : null
        }
      })
      .then(async response => {
        if (response.data.code === 200) {
          const rules = response.data.data;
          this.total = response.data.total || rules.length;

          // 获取所有分段计费数据
          const stageResponse = await this.$axios.get('/api/stageBilling/list');
          const stageData = stageResponse.data.code === 200 ? stageResponse.data.data : [];

          // 将分段计费数据关联到对应的规则
          this.tableData = rules.map(rule => {
            if (rule.status === 1) {
              // 找到该规则对应的所有分段计费数据
              const stages = stageData.filter(stage => 
                stage.billingRuleId === rule.id && stage.timeSlotType // 确保有时段类型和正确的关联ID
              );
              if (stages && stages.length > 0) {
                rule.stageBillings = stages.map(stage => ({
                  id: stage.id,
                  time_slot_type: stage.timeSlotType,
                  start_time: stage.startTime,
                  end_time: stage.endTime,
                  electricity_fee: stage.electricityFee,
                  charging_service_fee: stage.chargingServiceFee,
                  billing_rule_id: stage.billingRuleId,  // 保持ID关联
                  is_all_day: stage.isAllDay
                }));
              }
            }
            return rule;
          });
        } else {
          this.$message.error(response.data.msg || '获取计费规则列表失败');
        }
      })
      .catch(error => {
        console.error('获取计费规则列表失败:', error);
        this.$message.error('获取计费规则列表失败，请稍后重试');
      })
      .finally(() => {
        this.loading = false;
      });
    },

    handleAdd() {
      this.dialogTitle = '新增计费规则';
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.resetFields();
      });
    },

    handleEdit(row) {
      this.dialogTitle = '编辑计费规则';
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.formData = { 
          ...row,
          description: row.description || ''
        };
        
        // 如果是分段计费，使用已加载的数据
        if (row.status === 1) {
          if (row.stageBillings) {
            this.stageBillingData = row.stageBillings.map(stage => ({
              id: stage.id,
              time_slot_type: stage.time_slot_type,
              start_time: stage.start_time,
              end_time: stage.end_time,
              electricity_fee: stage.electricity_fee,
              charging_service_fee: stage.charging_service_fee,
              billing_rule_id: stage.billing_rule_id,
              is_all_day: stage.is_all_day
            }));
          } else {
            // 如果没有数据，初始化一个空的分段
            this.stageBillingData = [{
              id: null,
              time_slot_type: '尖',
              start_time: '00:00:00',
              end_time: '00:00:00',
              electricity_fee: '0.00',
              charging_service_fee: '0.00',
              billing_rule_id: row.id,
              is_all_day: 0
            }];
          }
        }
      });
    },

        /**
     * 处理表单提交逻辑
     * 该方法用于验证表单数据的有效性，并根据情况进行新增或编辑计费规则的操作。
     * 如果是新增规则，会先查询获取新增规则的ID，再创建分段计费数据；
     * 如果是编辑规则，会直接使用现有ID更新或创建分段计费数据。
     */
    handleSubmit() {
      // 验证表单数据
      this.$refs.formRef.validate(valid => {
        if (valid) {
          // 判断是编辑还是新增操作
          const isEdit = this.formData.id !== null;
          // 根据操作类型选择对应的API
          const api = isEdit ? '/api/billingRule/update' : '/api/billingRule/add';
          
          // 提交加载状态置为true
          this.submitLoading = true;
          // 先保存计费规则
          this.$axios.post(api, this.formData)
            .then(async response => {  // 使用 async/await
              if (response.data.code === 200) {
                // 如果是新增，先查询获取新增的计费规则ID
                if (!isEdit) {
                  // 查询最新的计费规则列表
                  const queryResponse = await this.$axios.get('/api/billingRule/list', {
                    params: {
                      pageNum: 1,
                      pageSize: 1,  // 只取最新的一条
                      keyword: this.formData.ruleName  // 用规则名称查询
                    }
                  });
                  
                  if (queryResponse.data.code === 200 && queryResponse.data.data.length > 0) {
                    const newRule = queryResponse.data.data[0];
                    console.log('查询到的新计费规则:', newRule);
                    
                    // 使用查询到的ID
                    if (this.formData.status === 1 && this.stageBillingData.length > 0) {
                      // 创建分段计费数据
                      const stageBillingPromises = this.stageBillingData.map(stage => {
                        const stageBilling = {
                          timeSlotType: stage.time_slot_type,
                          startTime: this.formatTime(stage.start_time),
                          endTime: this.formatTime(stage.end_time),
                          electricityFee: parseFloat(stage.electricity_fee || 0),
                          chargingServiceFee: parseFloat(stage.charging_service_fee || 0),
                          billingRuleId: newRule.id,  // 使用查询到的ID
                          isAllDay: 0
                        };

                        console.log('准备提交的分段计费数据:', stageBilling);

                        return this.$axios.post('/api/stageBilling/add', stageBilling);
                      });

                      // 等待所有分段计费数据提交完成
                      await Promise.all(stageBillingPromises);
                    }
                  }
                } else {
                  // 编辑模式，使用现有ID
                  if (this.formData.status === 1 && this.stageBillingData.length > 0) {
                    const stageBillingPromises = this.stageBillingData.map(stage => {
                      const stageBilling = {
                        timeSlotType: stage.time_slot_type,
                        startTime: this.formatTime(stage.start_time),
                        endTime: this.formatTime(stage.end_time),
                        electricityFee: parseFloat(stage.electricity_fee || 0),
                        chargingServiceFee: parseFloat(stage.charging_service_fee || 0),
                        billingRuleId: this.formData.id,
                        isAllDay: 0
                      };

                      // 如果存在分段ID，则添加到请求数据中
                      if (stage.id) {
                        stageBilling.id = stage.id;
                      }

                      return this.$axios.post(
                        stage.id ? '/api/stageBilling/update' : '/api/stageBilling/add',
                        stageBilling
                      );
                    });

                    // 等待所有分段计费数据提交完成
                    await Promise.all(stageBillingPromises);
                  }
                }

                // 提示操作成功
                this.$message.success(isEdit ? '修改成功' : '添加成功');
                // 关闭对话框
                this.dialogVisible = false;
                // 重新加载数据
                this.loadData();
              } else {
                // 抛出错误
                throw new Error(response.data.msg || '保存失败');
              }
            })
            .catch(error => {
              // 打印错误信息
              console.error('保存失败:', error);
              // 提示保存失败
              this.$message.error('保存失败，请稍后重试');
            })
            .finally(() => {
              // 提交加载状态置为false
              this.submitLoading = false;
            });
        }
      });
    },

    handleDelete(row) {
      this.$confirm('确认删除该计费规则吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/api/billingRule/${row.id}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功');
              this.loadData();
            } else {
              this.$message.error(response.data.msg || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除失败:', error);
            this.$message.error('删除失败，请稍后重试');
          });
      }).catch(() => {});
    },

    handleBatchDelete() {
      if (!this.selectedRows.length) return;
      
      this.$confirm(`确认删除选中的 ${this.selectedRows.length} 条记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const deletePromises = this.selectedRows.map(row => 
          this.$axios.delete(`/api/billingRule/${row.id}`)
        );

        Promise.all(deletePromises)
          .then(() => {
            this.$message.success('批量删除成功');
            this.loadData();
          })
          .catch(error => {
            console.error('批量删除失败:', error);
            this.$message.error('批量删除失败，请稍后重试');
          });
      }).catch(() => {});
    },

    handleDialogClose() {
      this.$refs.formRef.resetFields();
      this.formData = {
        id: null,
        ruleName: '',
        status: 2,
        description: '',
        uniformRate: 1.0,
        serviceRate: 0.6,
      };
      this.stageBillingData = [{
        id: null,
        time_slot_type: '尖',
        start_time: '00:00:00',
        end_time: '00:00:00',
        electricity_fee: '0.00',
        charging_service_fee: '0.00',
        billing_rule_id: null,
        is_all_day: 0
      }];
      this.dialogVisible = false;
    },

    handleSearch() {
      this.currentPage = 1;
      this.loadData();
    },

    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.currentPage = 1;
      this.loadData();
    },

    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.loadData();
    },

    handleAddStage() {
      const newStage = {
        id: null,
        time_slot_type: '尖',
        start_time: '00:00:00',
        end_time: '00:00:00',
        electricity_fee: '0.00',
        charging_service_fee: '0.00',
        billing_rule_id: this.formData.id,  // 设置当前计费规则ID
        is_all_day: 0
      };
      console.log('添加新阶段:', newStage);
      this.stageBillingData.push(newStage);
    },

    handleDeleteStage(index) {
      const stage = this.stageBillingData[index];
      if (stage.id) {
        this.$axios.delete(`/api/stageBilling/${stage.id}`)
          .then(response => {
            if (response.data.code === 200) {
              this.stageBillingData.splice(index, 1);
              this.$message.success('删除成功');
            } else {
              this.$message.error(response.data.msg || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除阶段计费失败:', error);
            this.$message.error('删除失败，请稍后重试');
          });
      } else {
        this.stageBillingData.splice(index, 1);
      }
    },

    formatTime(time) {
      if (!time) return '00:00:00';
      if (typeof time === 'string') {
        if (/^\d{2}:\d{2}:\d{2}$/.test(time)) return time;
        if (/^\d{2}:\d{2}$/.test(time)) return time + ':00';
      }
      if (time instanceof Date) {
        const hours = time.getHours().toString().padStart(2, '0');
        const minutes = time.getMinutes().toString().padStart(2, '0');
        return `${hours}:${minutes}:00`;
      }
      return '00:00:00';
    },

    // 格式化时段显示
    formatStageTimeSlots(stages) {
      if (!stages || !stages.length) return '暂无分段数据';
      return stages.map(stage => 
        `${stage.time_slot_type}(${this.formatTimeDisplay(stage.start_time)}-${this.formatTimeDisplay(stage.end_time)})`
      ).join(' ');
    },

    // 格式化价格显示
    formatStagePrices(stages) {
      if (!stages || !stages.length) return '暂无费率数据';
      return stages.map(stage => 
        `${stage.time_slot_type}(￥${stage.electricity_fee},￥${stage.charging_service_fee})`
      ).join(' ');
    },

    // 格式化时间显示
    formatTimeDisplay(time) {
      if (!time) return '';
      return time.substring(0, 5); // 只显示小时和分钟
    }
  },
  created() {
    this.loadData();
  }
}
</script>

<style scoped>
.billing-rule-manage {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.page-header i {
  font-size: 24px;
  margin-right: 10px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.unit-label {
  margin-left: 10px;
  color: #909399;
}

.separator {
  margin: 0 10px;
  color: #909399;
}

:deep(.el-table) {
  margin-top: 15px;
}

:deep(.el-button--text) {
  padding: 0 8px;
}

:deep(.el-button--text + .el-button--text) {
  margin-left: 0;
}

:deep(.el-tag) {
  text-transform: uppercase;
}

.time-period {
  display: inline-block;
  margin: 0 5px;
}

.rate-item {
  margin: 0 5px;
  color: #606266;
}

.rate-value {
  color: #409EFF;
  font-weight: bold;
}

.stage-billing-section {
  margin-top: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}
</style>
